# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2022-03-11 10:35:34
LastEditors: peng2.zhang
LastEditTime: 2022-03-14 11:05:00
'''
from datetime import datetime
import os
from os.path import dirname, abspath
from HTMLTable import HTMLTable
from HTMLTable.row import HTMLTableRow
from HTMLTable.cell import HTMLTableCell
from HTMLTable.common import HTMLTag

base_path = dirname(abspath(__file__))

daily_build_path = os.path.join(base_path, "..", "daily_build_history")
if not os.path.exists(daily_build_path):
    os.makedirs(daily_build_path)


class MyHTMLTag(HTMLTag):
    def to_html_inner_chips(self):
        chips = []
        chips.append(self.value)
        return chips

class MyHTMLTableCell(HTMLTableCell, MyHTMLTag):
    pass

class MyHTMLTableRow(HTMLTableRow, MyHTMLTag):

    def __init__(self, cells=(), is_header=False):
        list.__init__(self)
        MyHTMLTag.__init__(self, tag='tr')

        self.is_header = is_header

        self.append_cells(cells=cells)

    def append_cells(self, cells):
        cell_tag = 'th' if self.is_header else 'td'
        for cell in cells:
            self.append(MyHTMLTableCell(
                tag=cell_tag,
                value=cell,
            ))


class MyHTMLTable(HTMLTable, MyHTMLTag):
    def __init__(self, caption='', rows=()):
        list.__init__(self)
        MyHTMLTag.__init__(self, tag='table')

        self.caption = MyHTMLTag('caption')
        self.caption.set_value(value=caption)

        self.append_rows(rows=rows)

        self.colname2index = {}
        self.index2colname = {}

    def append_rows(self, rows, is_header=False):
        for row in rows:
            self.append(MyHTMLTableRow(
                cells=row,
                is_header=is_header,
            ))



class FormatToTable():
    def __init__(self, title, header_rows):
        self.title = title
        self.header_rows = header_rows
        self.table = MyHTMLTable(caption=self.title)
        #from code import interact
        #interact(local=locals())
        self.table.append_header_rows((
            tuple(self.header_rows),
            # ('名称', '构建结果', '构建分支', 'commit id', '提交时间', '提交者', '构建时间', 'job错误信息', 'job链接'),
        ))
        self.now_date = datetime.now().date()
        self.now_date_str = self.now_date.strftime('%Y-%m-%d')
    
    def exec_cmd(self, cmd):
        res = os.popen(cmd)
        # cmd_res = res.buffer.read().decode(encoding="utf-8")
        cmd_res = res.read()
        return cmd_res
    
    def append_datas(self, rows):
        self.table.append_data_rows(rows)

    def format_to_table(self, table_name="daily-build-table.html"):
        self.table_name = table_name
        self.table.caption.set_style({
            'font-size': '15px',
        })
        self.table.set_style({
            'border-collapse': 'collapse',
            'word-break': 'keep-all',
            'white-space': 'nowrap',
            'font-size': '14px',
            "-webkit-border-vertical-spacing": "0px",
            "-webkit-border-horizontal-spacing": "0px",

        })
        # 表头样式
        self.table.set_header_row_style({
            'color': '#fff',
            'background-color': '#48a6fb',
            'font-size': '18px',
        })
        self.table.set_data_row_style({
            "vertical-align": "top",
        })
        self.table.set_data_cell_style({
            "border": "1px solid #48a6fb",
            "padding": "5px",
        })
        # 覆盖表头单元格字体样式
        self.table.set_header_cell_style({
            'padding': '15px',
        })
        html = self.table.to_html()
        with open(os.path.join(daily_build_path, self.table_name), "w") as f:
            f.write(f"""<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head><title>{self.title}</title>""")
            f.write(html)
        self.exec_cmd(f"""qsctl cp {os.path.join(daily_build_path, self.table_name)} qs://autobuildtestline/daily_builld/{self.now_date_str}/ -c ~/.qingstor_config.yaml""")
        url = f"http://ecarx.stor.ecarx.com.cn/autobuildtestline/daily_builld/{self.now_date_str}/{self.table_name}"
        return url
